import { Card, Button, Typography, message } from 'antd'
import { PlayCircleOutlined, StopOutlined } from '@ant-design/icons'
import { useEffect, useState } from 'react'

const { Title } = Typography
let configValues = null

const StartStop = () => {
  const [frpStatus, setFrpStatus] = useState(false)

  const [logOutput, setLogOutput] = useState('')

  useEffect(() => {
    fetch('http://localhost:3001/frp-status')
      .then(res => res.json())
      .then(data => {
        setFrpStatus(data.running)
      })
  }, [])
  /**websocket 获取日志*/
  useEffect(() => {
    const ws = new WebSocket('ws://localhost:3002')

    ws.onmessage = event => {
      setLogOutput(prev => {
        const updated = prev + event.data
        localStorage.setItem('frp-log-cache', updated)
        return updated
      })
    }

    ws.onerror = err => {
      console.error('WebSocket 错误:', err)
    }
    
    // 初始加载缓存
    const savedLog = localStorage.getItem('frp-log-cache')
    if (savedLog) setLogOutput(savedLog)

    return () => {
      ws.close()
    }
  }, [])

  useEffect(() => {
    const cached = localStorage.getItem('frp-global-config')
    if (cached) {
      try {
        configValues = JSON.parse(cached)
      } catch {
        // 解析失败不做操作
      }
    }
  }, [])

  const toggleFrp = () => {
    
    frpStatus ? stopFrp() : startFrp()
    // message.success(`FRP ${frpStatus ? "已停止" : "已启动"}`);
  }

  /**启动frpc */
  const startFrp = async () => {
    console.log(111)
    if (!configValues) {
      message.warning('请先填写并保存配置')
      return
    }

    try {
      const res = await fetch('http://localhost:3001/start-frp', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(configValues),
      })

      const data = await res.json()
      if (res.ok) {
        setLogOutput(data.output)
        message.success('frpc 启动成功')
        setFrpStatus(!frpStatus)
      } else {
        message.error(data.error || '启动失败')
      }
    } catch (err) {
      message.error('请求失败')
    }
  }
  /**停止frpc */
  const stopFrp = async () => {
    try {
      const res = await fetch('http://localhost:3001/stop-frp', {
        method: 'POST',
      })
      const data = await res.json()
      if (res.ok) {
        message.success(data.message)
        setFrpStatus(!frpStatus)
      } else {
        // toggleFrp()
        message.error(data.error)
      }
    } catch (err) {
      message.error('停止失败')
    }
  }

  return (
    <div>
      <Card>
        <Title level={4}>FRP 启动/停止</Title>
        <Button
          type='primary'
          danger={frpStatus ? true : false}
          icon={frpStatus ? <StopOutlined /> : <PlayCircleOutlined />}
          onClick={toggleFrp}>
          {frpStatus ? '停止 FRP' : '启动 FRP'}
        </Button>
      </Card>
      <Card title='FRP 日志输出' style={{ marginTop: 24 }}>
        <pre
          style={{
            background: '#111',
            color: '#0f0',
            padding: 12,
            maxHeight: 400,
            overflow: 'auto',
          }}>
          {logOutput || '暂无日志'}
        </pre>
      </Card>
    </div>
  )
}

export default StartStop
